package View;

import Dao.Blog;
import Dao.BlogDao;
import Dao.User;
import Dao.UserDao;
import common.Util;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/details.html")
public class DetailsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");

        User user = Util.checkLoginStatus(req);
        if(user == null){
            resp.sendRedirect("login.html");
            return;
        }

        String str = req.getParameter("blogId");
        if(str == null || str.length() == 0){
            resp.getWriter().write("blogId缺失!");
            return;
        }
        int blogId = Integer.parseInt(str);
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.selectOne(blogId);
        if(blog == null){
            resp.getWriter().write("当前博客不存在!");
            return;
        }
        UserDao userDao = new UserDao();
        User author = userDao.selectById(blog.getUserId());
        TemplateEngine engine = (TemplateEngine) getServletContext().getAttribute("engine");
        WebContext webContext = new WebContext(req,resp,getServletContext());
        webContext.setVariable("blog",blog);
        webContext.setVariable("user",userDao.selectById(blog.getUserId()));
        webContext.setVariable("total",blogDao.selectTotal(author.getUserId()));
        webContext.setVariable("showDelete",user.getUserId() == blog.getUserId());
        engine.process("details",webContext,resp.getWriter());
    }
}
